package com.tau.egonetwork.net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import com.tau.egonetwork.common.Log;
import com.tau.egonetwork.exceptions.EgoNetworkException;

public class EgoNetworkRequest {

	public Object doRequest(IRequest request, IResponse response) throws Exception {
		return doRequest(request, response, null);
	}
		
	public Object doRequest(IRequest request, IResponse response, IExceptionHandler handler) throws Exception {
		
		Object parsedObject = null;
		HttpURLConnection conn = null;
		BufferedReader in = null;
		StringBuffer responseBuffer = null;
		
		try {
			
			String url = request.generateRequestURL();
			
			Log.writeLineToLog("Sending API request: " + url);
			
			URL obj = new URL(url);
			conn = (HttpURLConnection)obj.openConnection();
			conn.setRequestMethod("GET");
			conn.setRequestProperty("User-Agent", "Chrome");
									
			in = new BufferedReader(
			        new InputStreamReader(conn.getInputStream()));
			String inputLine;
			responseBuffer = new StringBuffer();
	 		
			while ((inputLine = in.readLine()) != null) {
				responseBuffer.append(inputLine);
			}
						
			parsedObject =  response.parseJSONResponse(responseBuffer.toString());
			
		} catch (EgoNetworkException e) {
			//exception has already been handled by subsequent call,
			//simply pass it along:
			throw e;
		} catch (Exception e) {
			
			Log.writeLineToLog("API request exception: " +
					"errorStream = " + (conn == null ? "conn is null" :
						(conn.getErrorStream() == null ? "conn.getErrorStream() is null" : conn.getErrorStream().toString()))
					+ " ; responseBuffer = " + (responseBuffer == null ?
							"responseBuffer is null" : responseBuffer.toString()));
			
			if (handler != null) {
				handler.onException(e,
						(conn == null ? null : conn.getErrorStream()));
			} else {
				//handler not supplied -- roll exception to calling point
				throw e;
			}
		} finally {
			try {
				if (in != null)
					in.close();
			} catch (IOException e) {
				Log.writeExceptionToLog(e);
			}
		}
		
		return parsedObject;
	}
}
